<?php

/**
 * ZView
 *
 * Zend Frameworks View Component for TYPO3
 *
 * @package    ZView
 * @copyright  Copyright (c) Zephir AG, www.zephir.ch
*/


/** Abstract class for extension */
require_once 'Zend/View/Helper/Abstract.php';

/**
 * Helper to parse plain text and transform it to html
 * Eg. 'www.test.com' becomes '<a href='www.test.com'>www.test.com</a>
 *
 * @package ZView
 * @copyright  Copyright (c) Zephir AG, www.zephir.ch
 */
class Tx_Zview_Helper_HtmlTransform extends Zend_View_Helper_Abstract
{

	/**
	 * The TYPO3 plugin
	 * @var tslib_pibase
	*/
	private $_pi;

	/**
	 * Transforms HTML content. This is the shortform of htmlTransform()->linksToHtml().
	 *
	 * If no arguments are passed, returns a Tx_Zview_Helper_Transformer object.
	 *
	 * @param string $input
	 * @return string|Tx_Zview_Helper_HtmlTransform
	 */
	public function htmlTransform($input = null)
	{
        if (0 == func_num_args()) {
            return $this;
        }
		return $this->linksToHtml($input);
	}


	/**
	 * Parses URLs and E-Mail addresses and transforms them to valid HTML tags
	 *
	 * @param string $input
	 * @return string
	*/
	public function linksToHtml($str) {
		$from	= array();
		$to		= array();
		foreach(preg_split('#\s#', $str) AS $word) {
			$word = trim($word);
			// Url
			if(substr($word, 0, 7) == 'http://') {
				$from[]	= $word;
				$to[]	= sprintf('<a target="_blank" href="%s">%s</a>', $word, $word);
			}
			else if(substr($word, 0, 4) == 'www.') {
				$from[]	= $word;
				$to[]	= sprintf('<a target="_blank" href="http://%s">%s</a>', $word, $word);
			}
			else if(t3lib_div::validEmail($word)) {
				$from[]	= $word;
				$to[]	= $this->_pi->cObj->getTypoLink($word, $word);
			}
		}
		if((count($from) > 0) && (count($to) > 0)) {
			return str_replace($from, $to, $str);
		}
		return $str;
	}




	/**
	 * Set the View object
	 *
	 * @param  Zend_View_Interface $view
	 * @return Zend_View_Helper_Abstract
	*/
	public function setView(Zend_View_Interface $view) {
		$this->view = $view;
		$this->_pi = $view->getPi();
		if(empty($this->_pi) || (!$this->_pi instanceof tslib_pibase)) {
			throw new Exception('Please set tslib_pibase using $view->setPi($this) in your plugin class.');
		}
		return $this;
	}



}



if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/zview/helper/HtmlTransform.php']) {
	include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/zview/helper/HtmlTransform.php']);
}


